<?php
namespace app\controller;

use app\BaseController;
use app\model\User;
use think\Request;
use app\controller\AuthToken;


class Test extends BaseController{

    //用户注册
    public  function register(Request $request)
    {
        $email=$request->param('email','');
        $password=$request->param('password','123456');
        $captcha=$request->param('captcha');//验证码
        $arr = [
            'email'=>$email,
            'password'=>$password,
        ];
        $this->validate($arr,'User');
        $data = [
            'captcha'=>$captcha,
        ];
        //校验验证码
        $this->validate($data,[
            'captcha|验证码'=>'require|captcha'
        ]);
        $dbData=['email'=>$email,'password'=>md5($password)];
        $user = User::create($dbData);
        if($user){
            return json(['uid'=>$user->id,'status'=>200,'info'=>'注册成功']);
        }else{
            return json(['status'=>100001,'info'=>'注册失败']);
        }
    }



    //用户登陆
    public function login(Request $request)
    {
        $auth=new \app\controller\AuthToken();
        $auth->checkToken(); //校验header中authorization是否存在
        $name=$request->param('email','bj@aa.com');
        $password=$request->param('password','123456');
        $captcha=$request->param('captcha');//验证码
        $arr = [
            'email'=>$name,
            'password'=>$password,
        ];
        $this->validate($arr,'User');
        $data = [
            'captcha'=>$captcha,
        ];
        //校验验证码
        $this->validate($data,[
            'captcha|验证码'=>'require|captcha'
        ]);
        $res=User::where($arr)->find();
        if($res){
            $res=['status'=>200,'info'=>'登陆成功',
                'jwt' => self::createJwt($res['id']),//生产token
            ];
            goto end;
        }else{
            $res=['status'=>1,'info'=>'账号或者密码错误，请您重新输入'];
            goto end;
        }
        end:
        return json($res);
    }

    //生成token
    public function createJwt($userId)
    {
        $key = md5('beijing'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $userId,
            "iss" => "https://www.baidu.com",//签发组织
            "aud" => "https://www.baidu.com", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }

    //生成验证码
    public function show_captcha($id = '')
    {
        return captcha($id);
    }
}